import puppeteer from 'puppeteer-core'
import {Page} from 'puppeteer-core'

const browserWSEndpoint = 'ws://127.0.0.1:9222/devtools/browser/84aa6b35-fe30-4a7b-ae12-d274c4ca931e';
const pageUrl = 'https://show.bilibili.com/platform/detail.html?id=99183&from=pc_ticketlist';
const selectedDate = 1;
const selectedTickets = 1;
const phone = '';
const username = '';
const useSelected = false;

(async () => {
  // 启动浏览器（默认无头模式）
  const browser = await puppeteer.connect({
    defaultViewport: null,
    browserWSEndpoint: browserWSEndpoint
  }).catch((errors) => {
    console.log(errors)
    throw errors
  })

  // 获取或创建页面
  /*const pages = await browser.pages();
  let page;

  if (pages.length > 0) {
    // 使用第一个已打开的页面
    page = pages[0];
    console.log('复用已有页面');
  } else {
    // 创建新页面
    page = await browser.newPage();
    console.log('创建新页面');
  }*/
  const page = await browser.newPage()

  await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36')

  // 导航到页面并截图
  //await page.goto('https://show.bilibili.com/platform/detail.html?id=100596&from=pc_ticketlist')
  //101496 101142 101955 101256 101969
  await page.goto(pageUrl)
  // await page.screenshot({ path: 'screenshot.png' })
  try {
    // 判断是否登入成功
    await page.click('.nav-header-register')
    // 等待该元素可见
    await page.waitForSelector(".bili-mini-tab-message", { visible: true, timeout: 2000})

    await page.click('.bili-mini-tab-message')
    // 输入文本
    await page.type('.tel-input', phone, { delay: 100 }); // 模拟人工输入
    // 方案一：轮询检测输入框内容变化（每 1 秒检查一次）
    await waitForInput(page, '.bili-mini-code >input', 300000); // 300000ms = 5分钟

    // 方案二：直接等待用户操作（注释掉上方代码，启用下方代码）
    // await page.waitForFunction(
    //   (selector) => document.querySelector(selector).value.length > 0,
    //   { timeout: 300000 },
    //   captchaSelector
    // );

    await page.click('.login-btn')

    // await page.waitForSelector(".product-buy >div", { visible: true })
    await page.waitForNavigation({ timeout: 10000 })
    await buyTickets(page)
  } catch (ex) {
    console.log('已经登入过')
    await buyTickets(page)
  }

})()

async function selectDate(page: Page){
  try {
    await page.click(`.screens >.selectable-option:nth-child(${selectedDate})`)
  } catch (e) {
    console.log(e)
  }
  try {
    await page.click(`.tickets >.selectable-option:nth-child(${selectedTickets})`)
  } catch (e) {
    console.log(e)
  }
}

async function buyTickets(page: Page){

  let canBuy = false
  let canBuyCount = 1

  //打印购买按钮值
  console.log(await page.evaluate(() => {
    const buyBtn = document.querySelector('.product-buy >div')
    return buyBtn?.textContent?.trim()
  }), 'btnValue')

  while (!canBuy){
    //选择日期或票种
    if (useSelected) await selectDate(page)

    canBuy = await page.evaluate(() => {
      const buyBtn = document.querySelector('.product-buy >div')
      if (buyBtn == null) return false
      return buyBtn.textContent?.trim() === '立即购票'
    })
    if (!canBuy) {
      await setTimeout(() => {}, 300)
      console.log(`等待${canBuyCount++}`)
      await page.reload()
    }
  }

  console.log(`buy=${canBuy}`)
  await page.click('.product-buy >div')
  //等待浏览器跳转
  await page.waitForNavigation({ timeout: 1000 })

  const checked = await page.evaluate(
    () => document.querySelector('.service-term >.check-icon.checked') !== null)
  console.log(`.check-icon.checked=${checked}`)
  if (!checked){
    await page.click('.service-term >.check-icon')
  }
  //await page.click('.service-term >.check-icon')

  // 填写个人信息
  let flag = await page.evaluate(() => {
    const username = document.querySelector('.info-content >.content-prop:first-child')
    if (username == null) return -1
    // @ts-ignore
    const value = username.querySelector('.input-value')?.value
    return value ? 1 : 0
  })

  if (flag === 0){
    await page.type('.info-content >.content-prop:first-child .input-value', username, { delay: 100 }); // 模拟人工输入
  }

  flag = await page.evaluate(() => {
    const username = document.querySelector('.info-content >.content-prop:last-child')
    if (username == null) return -1
    // @ts-ignore
    const value = username.querySelector('.input-value')?.value
    return value ? 1 : 0
  })

  if (flag === 0){
    await page.type('.info-content >.content-prop:last-child .input-value', phone, { delay: 100 }); // 模拟人工输入
  }

  let confirm = false
  let count = 1
  while (!confirm){
    confirm = await page.evaluate(
      () => document.querySelector('.confirm-paybtn.active') !== null)
    if (!confirm){
      await setTimeout(() => {}, 200)
      console.log(`等待${count++}`)
      await page.reload()
    }
  }
  console.log('准备提交订单啦')
  await page.click('.confirm-paybtn')
}

async function waitForInput(page: Page, selector: string, timeout: number) {
  const startTime = Date.now();
  while (Date.now() - startTime < timeout) {
    // @ts-ignore
    const inputValue = await page.$eval(selector, el => el.value);
    if (inputValue && inputValue.trim().length >= 6) { // 假设验证码至少4位
      return true;
    }
    await setTimeout(() => {}, 1000); // 每秒检查一次
  }
  throw new Error(`等待验证码输入超时（${timeout}ms）`);
}